package grouplife::Controller::Tuans;
use Moose;
use namespace::autoclean;
use Catalyst::Request::Upload;
use Catalyst::Log;
use Date::Parse;
use POSIX qw(strftime);

use grouplife::Model::Category::CategoryModel;
use grouplife::Model::Tuan::TuansSearchModel;
use grouplife::Model::Tuan::TuansCreateModel;
use grouplife::Model::UserTuan::UserTuanModel;
use grouplife::Model::UserTuan::UserTuanUpdateModel;
use grouplife::Model::Users::UsersSearchModel;
use grouplife::Model::Comments::CommentsForUsersModel;
use grouplife::Model::Comments::CommentsForTuanModel;
use grouplife::Model::TuanStore::TuanStoreSearchModel;
use grouplife::Model::Leimu::LeimuModel;
use grouplife::Model::Store::StoreSearchModel;
use grouplife::Model::CategoryTuan::CategoryTuanModel;
use grouplife::Model::UserTuanStores::UserTuanStoresModel;
use grouplife::Model::University::UniversityModel;
use grouplife::Model::FaHuo::FaHuoModel;
use grouplife::Model::FaHuoUniversity::FaHuoUniversityModel;
use Util::Email::SendEmail;
use Time::Piece;

BEGIN {extends 'Catalyst::Controller'; }
__PACKAGE__->config( 'Plugin::ConfigLoader' => { file => 'grouplife.yml' } );

=head1 NAME

grouplife::Controller::Tuans - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

    $c->response->body('Matched grouplife::Controller::Tuans in Tuans.');
}

=head2 list

Fetch all tuans and pass to tuans/list.tt2 in stash to be displayed

=cut

sub list :Local {
	my ($self, $c) = @_;

	$c->stash(login_user => $c->session->{login_user});
	$c->stash(cats => [$c->model('Category::CategoryModel')->get_all]);
	$c->stash(javascript => '/tuan/tuan_search.js');
	$c->stash(template => 'tuans/list.tt2');
}

sub tuan_paging :Local {
	my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $universities = $c->request->params->{"universities[]"} || '0';
        my $zhuangtai = $c->request->params->{"zhuangtai[]"} || '0';

	my %results;
	if ($universities eq '0' or $zhuangtai eq '0') {
		$c->stash(
			login_user => $c->session->{login_user},
			nowrapper => 1,
			template => 'tuans/tuan_search.tt2',
			tuans => \%results
		);
	} else {	
		unless(ref($universities) eq 'ARRAY') {
			my @arr = ($universities);
			$universities= \@arr;
		}
		unless(ref($zhuangtai) eq 'ARRAY') {
			my @arr = ($zhuangtai);
			$zhuangtai= \@arr;
		}
		my $tuans = $c->model('Tuan::TuansSearchModel')->tuan_search($universities, $zhuangtai, $start_index, $end_index);
		my %results;
		my $count = 0;
		foreach (@$tuans) {
			my $status = 'A';
			my $curr_time = `date --iso-8601=seconds`;
			if($_->status eq 'Y') {
				#if(str2time($curr_time) < str2time($_->zhifu_eff_to)) {
				#	$status = 'Z';
				#}elsif(str2time($curr_time) > str2time($_->fahuo_eff_to)) {
				#	$status = 'J';
				if(str2time($curr_time) < str2time($_->tihuo_time_from)) {
					$status = 'W';
				}elsif(str2time($curr_time) > str2time($_->tihuo_time_to)) {
					$status = 'J';
				}else {	
					$status = 'P';
				}	
			}
			if($_->status eq 'N') {
				$status = 'N';
			}
			$results{$count}{"id"} = $_->id;
			$results{$count}{"image"} = $_->image;
			$results{$count}{"name"} = $_->name;
			my @un = $_->university;
			$results{$count}{"university"} = \@un;
			$results{$count}{"status"} = $status;
			my @chengyuan = $_->member;
			if(@chengyuan) {
				$results{$count}{"buyer_count"} = scalar @chengyuan;
			} else {
			       $results{$count}{"buyer_count"} = 0;
			}
			$count ++;
		}

		$c->stash(
			login_user => $c->session->{login_user},
			nowrapper => 1,
			template => 'tuans/tuan_search.tt2',
			tuans => \%results
		);
	}
}

#Autocomplete in tuan search page
sub tuan_names:Local {
	my ($self, $c) = @_;
        my $p = $c->request->params->{q} || '';
	$c->res->output($c->model('Tuan::TuansSearchModel')->get_names_in_json($p));
}

sub user_selected : Local {
	my ($self, $c) = @_;
        my $tuanid = $c->request->params->{tuan_id};
        my $userid = $c->request->params->{user_id};

	$c->res->output($c->model('UserTuan::UserTuanModel')->get_options($userid, $tuanid));
}

sub select_options : Local {
	my ($self, $c) = @_;
        my $option = $c->request->params->{option};
        my $tuan_id= $c->request->params->{tuan_id};
        my $tuan_name= $c->request->params->{tuan_name};
        my $user_id= $c->request->params->{user_id};

	my $user_name = $c->model('Users::UsersSearchModel')->find($user_id)->username;
	$c->stash(login_user => $c->session->{login_user});
	$c->stash(user_id => $user_id);
	$c->stash(user_name => $user_name);
	$c->stash(javascript => '/tuan/tuan_info.js');
	$c->stash(nowrapper => 1);
	$c->stash(tuan_id => $tuan_id );
	$c->stash(tuan_name => $tuan_name );

	if($option == 1) {
		#delete
		$c->stash(template => "tuans/tuan_delete_user.tt2");
	}elsif($option == 2) {
		#change  from new to done
		$c->stash(template => "tuans/tuan_new_to_done.tt2");
	}elsif($option == 3) {
		#change from done to new
		$c->stash(template => "tuans/tuan_done_to_new.tt2");
	}
}

sub tuan_delete_user : Local{
        my ($self, $c) = @_;
	
        my $tuan_id= $c->request->params->{tuan_id};
        my $tuan_name= $c->request->params->{tuan_name};
        my $user_id= $c->request->params->{user_id};
	
	$c->model('UserTuan::UserTuanUpdateModel')->tuan_delete_user($tuan_id, $user_id);
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
}

sub tuan_search:Local {
	my ($self, $c) = @_;
        my $name = $c->request->params->{content} || '';
	
	my $universities = $c->model('University::UniversityModel')->get_all;

	$c->stash(
		login_user => $c->session->{login_user},
		javascript => '/tuan/tuan_search.js',
		content => $name,
		title => "搜索团购",
		universities=>$universities,
		css => 'tuan_search.css',
		cats => [$c->model('DB::Category')->all],
		template => 'tuans/list.tt2'
	);
}

sub tuan_total_by_name:Local {
	my ($self, $c) = @_;

        my $name = $c->request->params->{"name"} || '0';

	if ($name eq '0') {
		 $c->res->output(0);
	} else {	
		$c->res->output($c->model('Tuan::TuansSearchModel')->get_total_tuan_number_by_name($name));
	}
}
sub tuan_paging_by_name :Local {
	my ($self, $c) = @_;

        my $name = $c->request->params->{"name"} || '0';
        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
	my $page = $start_index / 10;
	$page = $page + 1;


	my %results;
	my $tuans = $c->model('Tuan::TuansSearchModel')->tuan_search_by_name($name, $page);
	my $count = 0;
	foreach (@$tuans) {
		my $status = 'A';
		my $curr_time = `date --iso-8601=seconds`;
		if($_->status eq 'Y') {
			#if(str2time($curr_time) < str2time($_->zhifu_eff_to)) {
			#	$status = 'Z';
			#}elsif(str2time($curr_time) > str2time($_->fahuo_eff_to)) {
			#	$status = 'J';
			if(str2time($curr_time) < str2time($_->tihuo_time_from)) {
				$status = 'W';
			}elsif(str2time($curr_time) > str2time($_->tihuo_time_to)) {
				$status = 'J';
			}else {	
				$status = 'P';
			}	
		}
		if($_->status eq 'N') {
			$status = 'N';
		}
		$results{$count}{"id"} = $_->id;
		$results{$count}{"image"} = $_->image;
		$results{$count}{"name"} = $_->name;
		my @un = $_->university;
		$results{$count}{"university"} = \@un;
		$results{$count}{"status"} = $status;
		my @chengyuan = $_->member;
		if(@chengyuan) {
			$results{$count}{"buyer_count"} = scalar @chengyuan;
		} else {
		       $results{$count}{"buyer_count"} = 0;
		}
		$count ++;
	}

	$c->stash(
		login_user => $c->session->{login_user},
		nowrapper => 1,
		template => 'tuans/tuan_search.tt2',
		tuans => \%results
	);
}

sub tuan_total:Local {
	my ($self, $c) = @_;

        my $universities = $c->request->params->{"universities[]"} || '0';
        my $zhuangtai = $c->request->params->{"zhuangtai[]"} || '0';

	if ($universities eq '0' or $zhuangtai eq '0') {
		 $c->res->output(0);
	} else {	
		unless(ref($universities) eq 'ARRAY') {
			my @arr = ($universities);
			$universities= \@arr;
		}
		unless(ref($zhuangtai) eq 'ARRAY') {
			my @arr = ($zhuangtai);
			$zhuangtai= \@arr;
		}
		$c->res->output($c->model('Tuan::TuansSearchModel')->get_total_tuan_number($universities, $zhuangtai));
	}
}

sub store_id:Chained('base'):PathPart('store_id'):CaptureArgs(1){
	my ($self, $c, $id) = @_;

	$c->stash(store => $c->model('Store::StoreSearchModel')->find($id));
}

sub form_create:Local{
	my ($self, $c) = @_;

	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		return 0;
	}
	$c->stash(login_user => $c->session->{login_user});
	$c->stash(template => 'tuans/form_create.tt2');
}

sub base :Chained('/') :PathPart('tuans') :CaptureArgs(0) {
	my ($self, $c) = @_;

	$c->stash(resultset => $c->model('DB::Tuan'));
}

sub comment:Chained('base') :PathPart('comment') :Args(0){
        my ( $self, $c ) = @_;
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                return 0;
        }

        my $comment = $c->request->params->{comment}  || '';
        my $comm_id= $c->request->params->{comm_id} || '';
        my $tuan_id= $c->request->params->{tuan_id} || '';
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
        $c->model('CommentedItem::CommentedItemModel')->add_to_comments($comm_id, $c->user->get('id'), $comment);
	$c->user->add_to_my_news({user_id=>$c->user->id, event_type_id=>5, photo=>$c->user->photo, me_name=>$c->user->username, target_id=>$tuan_id, target_name=>$tuan->name});

	$c->stash(comments => $c->model('Comments::CommentsForUsersModel')->search($comm_id),
		nowrapper=> 1,
		javascript => '/tuan/tuan_info.js',
		template => 'tuans/new_comment.tt2');
}

sub tuan_create : Local{
	my ($self, $c) = @_;
	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		return 0;
	}

	$c->stash(login_user => $c->session->{login_user},
		javascript => '/tuan/tuan_create.js',
		template => 'tuans/tuan_create.tt2');
}

sub join_tuan : Local{
        my ($self, $c) = @_;
	
	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

        my $tuan_id= $c->request->params->{tuan_id};
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
        my $user = $c->session->{login_user};
	my $stores = $c->model('UserTuanStores::UserTuanStoresModel')->search($user->id, $tuan_id);
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->find_user_tuan($tuan_id,$user->id);
	
	$c->stash(login_user => $c->session->{login_user},
		javascript => '/tuan/tuan_info.js',
		nowrapper => 1,
		session_username => $c->session->{$tuan_id}{user_name},
		session_useraddress => $c->session->{$tuan_id}{user_address},
		session_userphone => $c->session->{$tuan_id}{user_phone},
		tuan => $tuan,
		stores => $stores,
		user_tuan => $user_tuan,
		template => "tuans/join_tuan.tt2");
	
}

sub modify_pay_url : Local{
        my ($self, $c) = @_;
	
	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	my $tuan_id= $c->request->params->{tuan_id};
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);

	$c->stash(login_user => $c->session->{login_user},
		javascript => '/tuan/tuan_info.js',
		nowrapper => 1,
		tuan => $tuan,
		template => "tuans/modify_pay_url.tt2");
	
}

sub modify_pay_url_do : Local{
        my ($self, $c) = @_;
	
	my $tuan_id= $c->request->params->{tuan_id};
	my $pay_url= $c->request->params->{pay_url};
	
	$pay_url =~ s/^\s+//;
	$pay_url =~ s/\s+$//;

	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my $new_url = $pay_url;
	my $old_url = $tuan->pay_url;
	
	unless ($new_url eq $old_url ){
		$tuan->update({pay_url => $new_url});
		$c->stash(login_user => $c->session->{login_user},
			tuan_id => $tuan_id,
			old_url => $old_url,
			tuan_name => $tuan->name,
			css => 'about.css',
			new_url => $new_url,
			template => "tuans/modify_done.tt2");
	} else {
		$c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
	}
	
}

sub join_tuan_login : Local{
        my ($self, $c) = @_;
	
        my $tuan_id= $c->request->params->{tuan_id};
	$c->response->redirect($c->uri_for('/login'));
	$c->flash->{redirect_after_login} = '' . $c->req->base . "tuans/id/$tuan_id/tuan_info";
	return 0;

}

sub join_tuan_do : Local{
        my ($self, $c) = @_;
	
        my $amounts = $c->request->params->{'amount[]'};
        my $storeIds = $c->request->params->{'storeId[]'};
        my $tuan_id = $c->request->params->{tuan_id};
	my $user = $c->session->{login_user};
	my $rec_user_name = $c->request->params->{dinghuo_name};
	my $rec_user_address = $c->request->params->{address};
	my $rec_user_phone = $c->request->params->{cellphone};
	my $tuan_university = $c->request->params->{university} || '';

        unless(ref($storeIds) eq 'ARRAY') {
                my @arr = ($storeIds);
                $storeIds = \@arr;
        }
        unless(ref($amounts) eq 'ARRAY') {
                my @arr = ($amounts);
                $amounts = \@arr;
        }
	my @message;
	my %storeAmount;
	my $sign = 0;
	my $flag = 0;
	my $index = 0;
	if ($rec_user_name eq '') {
		my $text = "您没有输入订货人姓名";
		push(@message, $text);
	}

	if ($rec_user_address eq '') {
		my $text = "您没有输入收货人地址";
		push(@message, $text);
	}
	
	if ($rec_user_phone eq '') {
		my $text = "您没有输联系电话";
		push(@message, $text);
	}

	if ($tuan_university eq '') {
		my $text = "您参团时没有选择具体高校";
		push(@message, $text);
	}

	if($rec_user_phone =~ /^1[0-9]{10}$/) {	
	}
	else {
		my $text = "您输入的联系手机号码有误";
		push(@message, $text);
	}

	foreach (@$amounts) {
		if($_ != 0) {
			if(m/^[1-9]\d*/) {	
				if($_ >= 10000) {
					$sign = 1;
					my $text = "你输入的购买件数过大";
					push(@message, $text);
				} else {
					$sign = 1;
					my $storeId = $storeIds->[$index];
					$storeAmount{$storeId} = $_;
				}
			} else {
				$flag = 1;
			}
		}
		$index ++;
	}
	if($sign == 0) {
		my $text = "你没有选择购买任何商品";
		push(@message, $text);
	
	}
	if($flag == 1) {
		my $text = "你输入的购买件数不是合法的数字";
		push(@message, $text);
	}
	if(scalar(@message) != 0) {
		$c->session->{$tuan_id}{user_name} = $rec_user_name;
		$c->session->{$tuan_id}{user_address} = $rec_user_address;
		$c->session->{$tuan_id}{user_phone} = $rec_user_phone;

		$c->stash(login_user => $c->session->{login_user});
		$c->stash(messages => \@message);
		$c->stash(css   => 'zhuce.css');
		$c->stash(tuan_id => $tuan_id);
		$c->stash(template => 'tuans/join_tuan_failed.tt2');
	} else {	
		my $user_tuan = $c->model('UserTuan::UserTuanModel')->find_user_tuan($tuan_id, $user->id);
		unless(defined($user_tuan)) {
			my $rand = new String::Random;
			my $password = $rand->randpattern('nnnnnnnn');

			$user_tuan = $c->model('UserTuan::UserTuanUpdateModel')->join_tuan_new($tuan_id, $user->id, $password,$rec_user_name, $rec_user_address, $rec_user_phone, $tuan_university);
			my $ret = $c->model('UserTuanStores::UserTuanStoresModel')->create($user->id, $tuan_id, \%storeAmount);

#Send Email
			my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
			my (%params, %options);
			$options{INCLUDE_PATH} = $c->config->{email_template_path};
			$params{username} = $c->user->username;
			$params{email}  = $c->user->email_address;
			$params{password}  = $password;
			$params{tuan_name}  = $tuan->name;
			$params{tuan_id}  = $tuan->id;

			my $title = "参团成功";
			my $sender = Util::Email::SendEmail->new();
			my $template = "email/join_tuan_success.html.tt";
			$sender->send($c->user->email_address, $title, $template, \%params, \%options);

			$c->stash(login_user => $c->session->{login_user});
			$c->stash(password => $password);
			$c->stash(css   => 'zhuce.css');
			$c->stash(tuan_id => $tuan_id);
			$c->stash(user => $user);
			$c->stash(template => 'tuans/join_tuan_success.tt2');
		} else {
			$c->model('UserTuan::UserTuanModel')->update_contact_info($tuan_id,$user->id,$rec_user_name, $rec_user_address, $rec_user_phone, $tuan_university);	
			my (%amountUpdate, %amountDelete);
			my $stores_exist = $c->model('UserTuanStores::UserTuanStoresModel')->search($user->id, $tuan_id);
			foreach(keys(%$stores_exist)) {
				if(exists $storeAmount{$_}){ 
					if($stores_exist->{$_} != $storeAmount{$_}) {
						$amountUpdate{$_} = $storeAmount{$_};
					}
					delete $storeAmount{$_};
				} else {
						$amountDelete{$_} = 0;
				}
			}
			my $ret = $c->model('UserTuanStores::UserTuanStoresModel')->create($user->id, $tuan_id, \%storeAmount);
			$ret = $c->model('UserTuanStores::UserTuanStoresModel')->update($user->id, $tuan_id, \%amountUpdate);
			$ret = $c->model('UserTuanStores::UserTuanStoresModel')->delete($user->id, $tuan_id, \%amountDelete);
			$c->stash(login_user => $c->session->{login_user});
			$c->stash(css   => 'zhuce.css');
			$c->stash(tuan_id => $tuan_id);
			$c->stash(user => $user);
			$c->stash(template => 'tuans/update_tuan_success.tt2');
		}
	}
}

sub exit_tuan : Local{
        my ($self, $c) = @_;
	
        my $tuan_id= $c->request->params->{exit_tuanid};
	
	$c->model('UserTuan::UserTuanUpdateModel')->tuan_delete_user($tuan_id, $c->user->id);
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
}

sub create_do : Local{
        my ($self, $c) = @_;

        my $name = $c->request->params->{tuanname};
        my $description = $c->request->params->{neirong};
        my $group_qitian = $c->request->params->{group_qitian} || 'y';
        my $group_tiyan = $c->request->params->{group_tiyan} || '0';
        my $group_zhifu = $c->request->params->{group_zhifu} || 'a';
        my $storeIds = $c->request->params->{"storeId[]"} || '0';
        my $prices = $c->request->params->{"price[]"};
        my $tihuo_location = $c->request->params->{tihuo_location} || '0';
        my $taobao_link = $c->request->params->{taobao_link} || '0';
        my $tiyan_location = $c->request->params->{tiyan_location} || '0';
        my $tiyan_time_from = $c->request->params->{tiyan_time_from} || "1/1/2000 0:0:0";
        my $tiyan_time_to = $c->request->params->{tiyan_time_to} || "1/1/2000 0:0:0";
        my $tihuo_time_from = $c->request->params->{tihuo_time_from} || "1/1/2000 0:0:0";
        my $tihuo_time_to = $c->request->params->{tihuo_time_to} || "1/1/2000 0:0:0";
        my $tuanname = $c->request->params->{tuanname};
        my $universities = $c->request->params->{"university[]"} || '0';

	my @messages;
	if($group_tiyan eq 'y' and $tiyan_location eq '0') {
		my $text = "你选择了为买家提供售前体验，但却没有说明体验地点";
		push(@messages, $text);
	}
	if($group_zhifu eq 'a' and $tihuo_location eq '0') {
			my $text = "你选择了提货时付款，但却没有说明提货地点";
			push(@messages, $text);
	}
	if($group_zhifu eq 'c' and $taobao_link eq '0') {
		my $text = "淘宝支付链接为空";
		push(@messages, $text);
	} else {
		if($group_zhifu eq 'c') {
			unless($taobao_link  =~ /^http:\/\/.*/) {
				my $text = "你输入的淘宝支付链接无效";
				push(@messages, $text);
			}
		}
	}
	my $price_flag = 0;
	if($storeIds eq '0') {
		my $text = "你没有选择任何商品参加本次团购";
		push(@messages, $text);
	} else {
		unless(ref($prices) eq 'ARRAY') {
			my @arr = ($prices);
			$prices = \@arr;
		}
		foreach (@$prices) {
			unless($_ =~ /^[1-9]\d*\.?\d*$/) {
				$price_flag = 1;
			}
		}
		if($price_flag == 1) {
			my $text = "你输入的商品价格不是合法的数字";
			push(@messages, $text);

		}
	}

	if($universities eq '0') {
		my $text = "你没有选择任何目标高校";
		push(@messages, $text);
	}

	$tiyan_location = '' if ($tiyan_location eq '0');
	$tihuo_location = '' if ($tihuo_location eq '0');
	$taobao_link = '' if ($taobao_link eq '0');

	my ($tiyan_df, $tiyan_dt);
	if($group_tiyan eq 'y') {
		eval{
			$tiyan_df= Time::Piece->strptime($tiyan_time_from, "%m/%e/%Y %H:%M:%S");
			$tiyan_dt = Time::Piece->strptime($tiyan_time_to, "%m/%e/%Y %H:%M:%S");
		};
		if(!$tiyan_df or !$tiyan_dt or $@){
			my $text = "体验时间格式不对";
			push(@messages, $text);

		} else {
			my $diff = $tiyan_dt - $tiyan_df;
			if($diff <= 0) {
				my $text = "体验结束时间应当在开始时间之后";
				push(@messages, $text);
			
			}
		}
	} else {
		$tiyan_df= Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
		$tiyan_dt = Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
	}

	my ($tihuo_df, $tihuo_dt, $current_time);
	eval{
		$tihuo_df= Time::Piece->strptime($tihuo_time_from, "%m/%e/%Y %H:%M:%S");
		$tihuo_dt = Time::Piece->strptime($tihuo_time_to, "%m/%e/%Y %H:%M:%S");
		#$current_time = Time::Piece->strptime(localtime(), "%m/%e/%Y %H:%M:%S");
	};
	if(!$tihuo_df or !$tihuo_dt or $@){
		my $text = "开截团时间格式不对";
		push(@messages, $text);

	} else {
		my $diff = $tihuo_dt - $tihuo_df;
		#my $curr_diff = $tihuo_df - $current_time;
		if($diff <= 0) {
			my $text = "截团时间应当在开团时间之后";
			push(@messages, $text);
		}
		#else {
		#	if($curr_diff <= 0) {
		#		my $text = "开团时间必须晚于当前时间";
		#		push(@messages, $text);
		#	}
		#}
	}
	
	if(scalar(@messages) != 0) {
		my $curr_time = `date --iso-8601=seconds`;
		
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(messages => \@messages);
		$c->stash(curr_time => $curr_time);
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'tuans/tuan_create_failed.tt2');
		$c->flash(newTuanName => $name);
		$c->flash(newTuanDesc => $description);
		$c->flash(newTuan_qitian => $group_qitian);
		$c->flash(newTuan_tiyan => $group_tiyan);
		$c->flash(newTuan_zhifu => $group_zhifu);
		$c->flash(taobao_link => $taobao_link);
		$c->flash(newTuan_tihuoloc => $tihuo_location);
		$c->flash(newTuan_tiyanloc => $tiyan_location);
		$c->flash(newTuan_tiyantimef => $tiyan_time_from);
		$c->flash(newTuan_tiyantimet => $tiyan_time_to);
		$c->flash(newTuan_tihuotimef => $tihuo_time_from);
		$c->flash(newTuan_tihuotimet => $tihuo_time_to);
		#$c->flash(newTuan_=> $tuanname);
		$c->flash(newTuan_univer => $universities);
		$c->flash(newTuan_storeIds => $storeIds);
		$c->flash(newTuan_prices => $prices);
	} else {
		unless(ref($universities) eq 'ARRAY') {
			my @arr = ($universities);
			$universities= \@arr;
		}
		unless(ref($storeIds) eq 'ARRAY') {
			my @arr = ($storeIds);
			$storeIds = \@arr;
		}

		my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('3');
		my $image = $c->request->upload('tuanimage');

		my $tuan = $c->model('Tuan::TuansCreateModel')->create($image, $c->config->{image_path}, $tuanname, $description, $commented_item->id, $c->user->id, $storeIds, $prices, $group_qitian, $group_tiyan, $group_zhifu, $tihuo_df, $tihuo_dt, $tihuo_location, $tiyan_df, $tiyan_dt, $tiyan_location, $universities, $taobao_link);
		#my $tuan = $c->model('Tuan::TuansCreateModel')->create($image, $c->config->{image_path}, $tuanname, $description, $commented_item->id, $c->user->id, $storeIds, $prices, $group_qitian, $group_tiyan, $group_zhifu, $tihuo_df, $tihuo_dt, $tiyan_df, $tiyan_dt, $tiyan_location, $universities, $taobao_link);
		$c->user->add_to_my_news({user_id=>$c->user->id, photo=>$c->user->photo, me_name=>$c->user->username, event_type_id=>3, target_id=>$tuan->id, target_name=>$tuan->name});

		$c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan->id]));
	}
}

sub object :Chained('base') :PathPart('id') :CaptureArgs(1) {
	my ($self, $c, $id) = @_;

	$c->stash(object => $c->stash->{resultset}->find($id));

	die "Tuan $id not found!" if !$c->stash->{object};

}

sub tuan_info :Chained('object') :PathPart('tuan_info') :Args(0) {
	my ($self, $c) = @_;

	$c->cache_page( $c->config->{time_out} );
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->get_owner($c->stash->{object}->id);
	my $tuan_name = $c->stash->{object}->name;

	my $create_user = $c->model('Users::UsersSearchModel')->find($user_tuan->get_column('user_id')->first()); 

	my $login_user_role = $c->model('UserTuan::UserTuanModel')->get_login_user_role($c->stash->{object}->id, $c->user, $c->session->{login_user});

	my $login_user_tuan;
	if($c->user_exists) {
		$login_user_tuan = $c->model('UserTuan::UserTuanModel')->find_user_tuan($c->stash->{object}->id, $c->user->id);
	}

	my $user_count = $c->model('UserTuanStores::UserTuanStoresModel')->get_user_count($c->stash->{object}->id);
	my $buy_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_amount($c->stash->{object}->id);
	my $chengyuan = $c->model('UserTuanStores::UserTuanStoresModel')->get_chengyuan($c->stash->{object}->id);

	my $fahuo_count = $c->model('FaHuo::FaHuoModel')->find_next_fahuo_count($c->stash->{object}->id);
	my @fahuo_records = $c->model('FaHuo::FaHuoModel')->fahuo_search($c->stash->{object}->id);	
	
	my @fahuo_universities;

	foreach my $fahuo (@fahuo_records) {
		my @fahuo_univs = $c->model('FaHuoUniversity::FaHuoUniversityModel')->fahuo_univ_search($fahuo->id);	
                push(@fahuo_universities, @fahuo_univs);
	}
	my $total_count = 0;
	if(defined($chengyuan)) {
		$total_count = scalar(@$chengyuan);
	}

#decide whether it is out of date
	my $my_tuan = $c->stash->{object};
	my $status = 'A';
	my $curr_time = `date --iso-8601=seconds`;
	if($my_tuan->status eq 'Y') {
		#if(str2time($curr_time) < str2time($my_tuan->zhifu_eff_to)) {
		#	$status = 'Z';
		#}elsif(str2time($curr_time) > str2time($my_tuan->fahuo_eff_to)) {
		#	$status = 'J';
		# W表示尚未开团
		if(str2time($curr_time) < str2time($my_tuan->tihuo_time_from)) {
			$status = 'W';
		# J表示团购已截团中
		}elsif(str2time($curr_time) > str2time($my_tuan->tihuo_time_to)) {
			$status = 'J';
		# P表示团购进行中
		}else {	
			$status = 'P';
		}	
	}
	if($my_tuan->status eq 'N') {
		$status = 'N';
	}

	$c->stash(login_user_role => $login_user_role,
		tuanid => $c->stash->{object}->id,
		tuanname => $c->stash->{object}->name,
		login_user => $c->session->{login_user},
		create_user => $create_user,
		tuan => $c->stash->{object},
		css => 'tuan_mainpage.css',
		total_count => $total_count,
		title => $tuan_name,
		status => $status,
		user_count => $user_count,
		buy_amount => $buy_amount,
		chengyuan => $chengyuan,
		fahuo_count => $fahuo_count,
		fahuo_records => \@fahuo_records,
		fahuo_univs => \@fahuo_universities,
		login_user_tuan => $login_user_tuan,
		javascript => '/tuan/tuan_info.js',
		template => 'tuans/tuan_mainpage.tt2');
}

sub buyer_list:Local {
        my ($self, $c) = @_;
        my $tuan_id = $c->request->params->{tuan_id};
        my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	unless(defined($tuan)) {
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'tuans/buyer_list_failed.tt2');
	}

	my $user_count = $c->model('UserTuanStores::UserTuanStoresModel')->get_user_count($tuan_id);
	my $buy_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_amount($tuan_id);
	my $buyer_details = $c->model('UserTuanStores::UserTuanStoresModel')->get_user_buy_details($tuan_id);
	my $bianhao = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_bianhao($tuan_id);
	my $price = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_price($tuan_id);
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();
	my @user_tuans = $c->model('UserTuan::UserTuanModel')->find_user_tuan_by_tuan_id($tuan_id);
	
	$c->stash(
		login_user => $c->session->{login_user},
		tuan => $tuan,
		css => 'tuan_mainpage.css',
		user_count => $user_count,
		owner_id => $owner_id,
		buy_amount => $buy_amount,
		title => $tuan->name,
		buyer_details => $buyer_details,
		bianhao => $bianhao,
		price => $price,
		user_tuans => \@user_tuans,
		template => 'tuans/buyer_list_detailed.tt2');
}

sub comments_total:Local {
        my ($self, $c) = @_;
        my $tuan_id = $c->request->params->{tuan_id};
        my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
        $c->res->output($c->model('Comments::CommentsForTuanModel')->get_comm_count($tuan->comm_item_id));
}

sub comments_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $tuan_id = $c->request->params->{tuan_id};
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();	

        my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
        my $page = $start_index / 10;
        $page = $page + 1;
        $c->stash(
                nowrapper => 1,
		owner_id => $owner_id,
		comments => $c->model('Comments::CommentsForTuanModel')->search($tuan->comm_item_id, $page),
                template => 'tuans/user_comments.tt2'
        );
}

sub update_tuan:Local {
	my ($self, $c) = @_;

	my $name = $c->request->params->{tuanname};
        my $description = $c->request->params->{neirong};
        my $group_qitian = $c->request->params->{group_qitian} || 'y';
        my $group_tiyan = $c->request->params->{group_tiyan} || '0';
        my $group_zhifu = $c->request->params->{group_zhifu} || 'a';
        my $storeIds = $c->request->params->{"storeId[]"} || '0';
        my $prices = $c->request->params->{"price[]"};
        my $tihuo_location = $c->request->params->{tihuo_location} || '0';
        my $tiyan_location = $c->request->params->{tiyan_location} || '0';
        my $tiyan_time_from = $c->request->params->{tiyan_time_from} || "1/1/2000 0:0:0";
        my $tiyan_time_to = $c->request->params->{tiyan_time_to} || "1/1/2000 0:0:0";
        my $tihuo_time_from = $c->request->params->{tihuo_time_from} || "1/1/2000 0:0:0";
        my $tihuo_time_to = $c->request->params->{tihuo_time_to} || "1/1/2000 0:0:0";
        my $tuanname = $c->request->params->{tuanname};
        my $universities = $c->request->params->{"university[]"} || '0';

	my @messages;
        if($group_tiyan eq 'y' and $tiyan_location eq '0') {
                my $text = "你选择了为买家提供售前体验，但却没有说明体验地点";
                push(@messages, $text);
        }
        if($group_zhifu eq 'a' and $tihuo_location eq '0') {
                my $text = "你选择了提货时付款，但却没有说明提货地点";
                push(@messages, $text);
        }
        if($storeIds eq '0') {
                my $text = "你没有选择任何商品参加本次团购";
                push(@messages, $text);
        }
        if($universities eq '0') {
                my $text = "你没有选择任何目标高校";
                push(@messages, $text);
        }
	unless(ref($prices) eq 'ARRAY') {
                my @arr = ($prices);
                $prices = \@arr;
        }

        my $price_flag = 0;
        foreach (@$prices) {
                unless($_ =~ /^[1-9]\d*\.?\d*$/) {
                        $price_flag = 1;
                }
        }
        if($price_flag == 1) {
                my $text = "你输入的商品价格不是合法的数字";
                push(@messages, $text);

        }

        my ($tiyan_df, $tiyan_dt);
        if($group_tiyan eq 'y') {
	        eval{
                        $tiyan_df= Time::Piece->strptime($tiyan_time_from, "%m/%e/%Y %H:%M:%S");
                        $tiyan_dt = Time::Piece->strptime($tiyan_time_to, "%m/%e/%Y %H:%M:%S");
                };
                if(!$tiyan_df or !$tiyan_dt or $@){
                        my $text = "体验时间格式不对";
                        push(@messages, $text);

                } else {
                        my $diff = $tiyan_dt - $tiyan_df;
                        if($diff <= 0) {
                                my $text = "体验结束时间应当在开始时间之后";
                                push(@messages, $text);

                        }
                }
        } else {
                $tiyan_df= Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
		$tiyan_dt = Time::Piece->strptime("1/1/2000 00:00:00", "%m/%e/%Y %H:%M:%S");
        }

	my ($tihuo_df, $tihuo_dt, $current_time);
	eval{
		$tihuo_df= Time::Piece->strptime($tihuo_time_from, "%m/%e/%Y %H:%M:%S");
		$tihuo_dt = Time::Piece->strptime($tihuo_time_to, "%m/%e/%Y %H:%M:%S");
		#$current_time = Time::Piece->strptime(localtime(), "%m/%e/%Y %H:%M:%S");
	};
	if(!$tihuo_df or !$tihuo_dt or $@){
		my $text = "开截团时间格式不对";
		push(@messages, $text);

	} else {
		my $diff = $tihuo_dt - $tihuo_df;
		#my $curr_diff = $tihuo_df - $current_time;
		if($diff <= 0) {
			my $text = "截团时间应当在开团时间之后";
			push(@messages, $text);
		}
		#else {
		#	if($curr_diff <= 0) {
		#		my $text = "开团时间必须晚于当前时间";
		#		push(@messages, $text);
		#	}
		#}
	}
	if(scalar(@messages) != 0) {
	        $c->stash(login_user => $c->session->{login_user});
                $c->stash(messages => \@messages);
                $c->stash(css   => 'zhuce.css');
                $c->stash(template => 'tuans/tuan_create_failed.tt2');	
	} else {
                unless(ref($universities) eq 'ARRAY') {
                        my @arr = ($universities);
                        $universities= \@arr;
                }
                unless(ref($storeIds) eq 'ARRAY') {
                        my @arr = ($storeIds);
                        $storeIds = \@arr;
                }

                my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('3');
                my $image = $c->request->upload('tuanimage');

		my $tuan_id = $c->request->params->{tuan_id};
                my $tuan = $c->model('Tuan::TuansCreateModel')->update($image, $c->config->{image_path}, $tuanname, $description, $commented_item->id, $c->user->id, $storeIds, $prices, $group_qitian, $group_tiyan, $group_zhifu, $tihuo_df, $tihuo_dt, $tihuo_location, $tiyan_df, $tiyan_dt, $tiyan_location, $universities, $tuan_id);
                #my $tuan = $c->model('Tuan::TuansCreateModel')->update($image, $c->config->{image_path}, $tuanname, $description, $commented_item->id, $c->user->id, $storeIds, $prices, $group_qitian, $group_tiyan, $group_zhifu, $tihuo_df, $tihuo_dt, $tiyan_df, $tiyan_dt, $tiyan_location, $universities, $tuan_id);
		$tuan = $c->model('Tuan::TuansCreateModel')->update_status('A', $tuan_id);
        	$c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
	}
}

sub jujue:Local {
        my ($self, $c) = @_;

        my $tuan_id = $c->request->params->{tuan_id};
        my $reject_comment = $c->request->params->{reject_comment_hidden};
	my $tuan = $c->model('Tuan::TuansCreateModel')->update_status('N', $tuan_id);
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();	
	my $owner = $c->model('Users::UsersSearchModel')->find($owner_id);		
	my $owner_address = $owner->email_address;		
	my $owner_name= $owner->username;		
	my $title = "您在随你团申请开通的团购需要更进一步的信息";
	my $sender = Util::Email::SendEmail->new();
        my $template = "email/rejectTuan.html.tt";
	my $tuan_url = $c->config->{tuan_info_uri} . "/" . $tuan_id . "/tuan_info";
	my (%params, %options);
	$options{INCLUDE_PATH} = $c->config->{email_template_path};
	$params{username} = $owner_name;
	$params{tuanname} = $tuan->name;
	$params{conf_url} = $tuan_url;
	$params{reject_time} = `date`;
	$params{reject_comment} = $reject_comment;
        $sender->send($owner_address, $title, $template, \%params, \%options);
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));
}

sub pizhun:Local {
        my ($self, $c) = @_;

        my $tuan_id = $c->request->params->{tuan_id};
	#my $one_week_later = `date --date='7 day' +%F`;
	#my $nine_days_later = `date --date='9 day' +%F`;
	#my $tuan = $c->model('Tuan::TuansCreateModel')->update_status('Y', $tuan_id, $one_week_later, $nine_days_later);
	my $tuan = $c->model('Tuan::TuansCreateModel')->update_status('Y', $tuan_id);
	#send mail to group creater
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();	
	my $owner = $c->model('Users::UsersSearchModel')->find($owner_id);		
	my $owner_address = $owner->email_address;		
	my $owner_name= $owner->username;		
	my $title = "您在随你团申请开通的团购已被批准";
	my $sender = Util::Email::SendEmail->new();
        my $template = "email/approveTuan.html.tt";
	my $tuan_url = $c->config->{tuan_info_uri} . "/" . $tuan_id . "/tuan_info";
	my (%params, %options);
	$options{INCLUDE_PATH} = $c->config->{email_template_path};
	$params{username} = $owner_name;
	$params{tuanname} = $tuan->name;
	$params{conf_url} = $tuan_url;
	$params{approve_time} = `date`;
        $sender->send($owner_address, $title, $template, \%params, \%options);
	#send mail to user who cares this tuan
	my $storeIds = $c->model('TuanStore::TuanStoreModel')->get_stores_bianhao($tuan_id);
	$title = "您在随你团关注的商品已经正式开团啦";
	$template = "email/notifyUserTuan.html.tt";
	foreach my $store_id(keys %$storeIds) {
		my $store = $c->model("Store::StoreSearchModel")->find($store_id);
		$params{storename} = $store->name;
		my @users = $c->model('UserStore::UserStoreModel')->get_unnotified_user($store_id)->all;	
		foreach my $user_id1( @users){
			my $emailUser = $c->model('Users::UsersSearchModel')->find($user_id1->user_id);
			$params{username} = $emailUser->username;
			$sender->send($emailUser->email_address, $title, $template, \%params, \%options);			
		}
		$c->model('UserStore::UserStoreModel')->update_notify_status($store_id);
	}
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));

}

sub deliveryGoodsConfirm:Local {
	my ($self, $c) = @_;
	my $user_tuan_id = $c->request->params->{user_tuan_id};
	
	
	#判断该用户是否已经登录
	if(!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	#判断该用户是否订货用户
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->find($user_tuan_id)->first();
	my $current_id = $c->session->{login_user}->id;
	my @messages;
	if ($current_id ne $user_tuan->user_id ) {
		my $text = "您不能确认该团购项目，请确保您已正确登录";
		push(@messages, $text);
	}
	if($user_tuan->role ne 'F') {
		my $text = "该订单可能尚未发货，或者已经确认收货，目前不能进行确认操作";
		push(@messages, $text);
	}
	if(scalar(@messages) != 0) {
		$c->stash(login_user => $c->session->{login_user});
                $c->stash(messages => \@messages);
                $c->stash(css   => 'zhuce.css');
                $c->stash(template => 'tuans/delivery_good_confirm_failed.tt2');
	} else {
		$c->model('UserTuan::UserTuanModel')->update_status($user_tuan_id,'Q');
		$c->stash(login_user => $c->session->{login_user});
                $c->stash(css   => 'zhuce.css');
		$c->stash(tuan_id => $user_tuan->tuan_id);
                $c->stash(template => 'tuans/delivery_good_confirm_success.tt2');
	}
			

	#返回团购确认页面
}

sub deliveryGoods:Local {
	my ($self, $c) = @_;
	my $user_tuan_id = $c->request->params->{user_tuan_id};
	
	my $user_tuan = $c->model('UserTuan::UserTuanModel')->find($user_tuan_id)->first();
        my $tuan_id = $c->request->params->{tuan_id};
        my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my $owner_id = $c->model('UserTuan::UserTuanModel')->get_owner($tuan_id)->get_column('user_id')->first();
	my $current_id = $c->session->{login_user}->id;
	#只有团长可以发送提醒邮件
	unless($current_id eq $owner_id) {
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'tuans/delivery_good_failed.tt2');
	}
		
	$c->model('UserTuan::UserTuanModel')->update_status($user_tuan_id,'F');
	#发送待确认邮件给参团人员
        my $sender = Util::Email::SendEmail->new();
        my $tuan_url = $c->config->{delivery_confirm_uri} . "?user_tuan_id=" . $user_tuan_id ;
       	my (%params, %options);
       	$options{INCLUDE_PATH} = $c->config->{email_template_path};
       	$params{conf_url} = $tuan_url;
       	$params{approve_time} = `date`;
       	my $title = "请确认您已收到随你团的团购货品";
       	my $template = "email/notifyUserDeliveryConfirm.html.tt";
       	$params{tuanname} = $tuan->name;
        my $user_id = $user_tuan->user_id;
        my $emailUser = $c->model('Users::UsersSearchModel')->find($user_id);
        $params{username} = $emailUser->username;
        $sender->send($emailUser->email_address, $title, $template, \%params, \%options);
	
	#返回购买列表页面	
	unless(defined($tuan)) {
		$c->stash(login_user => $c->session->{login_user});
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'tuans/buyer_list_failed.tt2');
	}

	my $user_count = $c->model('UserTuanStores::UserTuanStoresModel')->get_user_count($tuan_id);
	my $buy_amount = $c->model('UserTuanStores::UserTuanStoresModel')->get_amount($tuan_id);
	my $bianhao = $c->model('TuanStore::TuanStoreSearchModel')->get_stores_bianhao($tuan_id);
	my @user_tuans = $c->model('UserTuan::UserTuanModel')->find_user_tuan_by_tuan_id($tuan_id);
	
	$c->stash(
		login_user => $c->session->{login_user},
		tuan => $tuan,
		css => 'tuan_mainpage.css',
		user_count => $user_count,
		owner_id => $owner_id,
		buy_amount => $buy_amount,
		title => $tuan->name,
		bianhao => $bianhao,
		user_tuans => \@user_tuans,
		template => 'tuans/buyer_list_detailed.tt2');
}

sub notifyDelivery:Local {
       my ($self, $c) = @_;
       my $tuan_id = $c->request->params->{tuan_id};
       my $fa_address = $c->request->params->{fahuo_address_hidden};
       my $fa_time = $c->request->params->{fahuo_time_hidden} || '';
       my $fa_comment= $c->request->params->{fahuo_comment_hidden} || '';
       my $universities = $c->request->params->{fahuo_university_hidden} || '';
       my @arr = split(/,/,$universities);
       my @messages;
	if ($fa_time eq '' ) {
		my $text = "您没有输入发货时间";
		push(@messages, $text);
	}
	if ($fa_address eq '') {
		my $text = "您没有输入发货地点";
		push(@messages, $text);
	}
	if ($universities eq '') {
		my $text = "您没有选择本次发货覆盖的高校";
		push(@messages, $text);
	}
	if (scalar(@messages) != 0) {
		$c->stash(login_user => $c->session->{login_user});
                $c->stash(messages => \@messages);
                $c->stash(css   => 'zhuce.css');
                $c->stash(tuan_id => $tuan_id);
                $c->stash(template => 'tuans/notify_delivery_failed.tt2');
		return 1;
	} 

       my $me_id = $c->user->id;
       my $fahuo_count = $c->model('FaHuo::FaHuoModel')->find_next_fahuo_count($tuan_id);
       my $fahuo = $c->model('FaHuo::FaHuoModel')->add_to_fahuo($tuan_id,$fa_time,$fa_address,$fa_comment,$fahuo_count,$me_id);
       my $univ_text = '';
       foreach my $univ_id(@arr) {
		if($univ_id ne '')
		{
        		$c->model('FaHuoUniversity::FaHuoUniversityModel')->add_to_fahuo_university($fahuo->id,$univ_id,$me_id);
			my $univ = $c->model('University::UniversityModel')->find($univ_id);
			$univ_text = $univ_text . '【' . $univ->name . '】 ';
		}
       }

       my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
       my $sender = Util::Email::SendEmail->new();
       my $tuan_url = $c->config->{tuan_info_uri} . "/" . $tuan_id . "/tuan_info";
       my (%params, %options);
       $options{INCLUDE_PATH} = $c->config->{email_template_path};
       $params{conf_url} = $tuan_url;
       $params{approve_time} = `date`;
       $params{fa_comment} = $fa_comment;
       $params{fa_time} = $fa_time;
       $params{fa_address} = $fa_address;
       $params{cover_univ} = $univ_text;
       my @userTuans = $c->model('UserTuan::UserTuanModel')->find_user_tuan_by_tuan_id($tuan_id);
       my $title = "您在随你团参加的团购已经开始发货啦";
       my $template = "email/notifyUserDelivery.html.tt";
       $params{tuanname} = $tuan->name;
       foreach my $userTuan(@userTuans) {
               if($userTuan->role eq 'J') {
		       my $to_send = 0;
		       foreach my $univ_id(@arr) {
			  if($userTuan->university_id == $univ_id)
			  {
				$to_send = 1;
			  }
		       }
		       #只给注册在该高校的团员发送提醒邮件
		       if($to_send == 1) {
		       my %ding_dan_detail = ();
                       my $user_id = $userTuan->user_id;
                       my $emailUser = $c->model('Users::UsersSearchModel')->find($user_id);
		       my @utss = $c->model('UserTuanStores::UserTuanStoresModel')->search_user_tuan_store_by_id($user_id,$tuan_id);
		       my $details = "";
		       foreach my $user_tuan_store(@utss) {
				my $store = $c->model('Store::StoreSearchModel')->find($user_tuan_store->stores_id);
				$ding_dan_detail{$store->name} = $user_tuan_store->amount;
				$details = $details . $store->name . "|" . $user_tuan_store->amount . ";";
		       }
                       #$params{dingdan} = %ding_dan_detail;
                       $params{dingdan} = $details;
                       $params{username} = $emailUser->username;
                       $params{contact_name} = $userTuan->user_name;
                       $params{contact_address} = $userTuan->user_address;
                       $params{contact_phone} = $userTuan->user_cellphone;
                       $sender->send($emailUser->email_address, $title, $template, \%params, \%options);
		       }
               }
       }
        $c->response->redirect($c->uri_for($c->controller('Tuans')->action_for('tuan_info'), [$tuan_id]));

}


=head1 AUTHOR

lijie,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

